package com.itmayiedu.controller;

import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.feign.CallBackServiceFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author cht 【wonderfor@vip.qq.com】
 * @Date 2018/11/6
 */
@RequestMapping("/alibaba/callBack")
@Slf4j
@Controller
public class CallBackController {

    private static final String PAY_SUCCESS = "pay_success";

    @Autowired
    private CallBackServiceFeign callBackServiceFeign;

    //同步通知
    @RequestMapping("/returnUrl")
    public void synCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("######支付宝同步回调CallBackController######synCallBack开始,params:{}", params);
        ResponseBase responseBase = callBackServiceFeign.synCallBack(params);
        if(!responseBase.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
            //报错页面
            return;
        }
        PrintWriter writer =  response.getWriter();
        LinkedHashMap data = (LinkedHashMap) responseBase.getData();
        //商户订单号
        String outTradeNo = (String) data.get("outTradeNo");
        //支付宝交易号
        String tradeNo = (String) data.get("tradeNo");
        //付款金额
        String totalAmount = (String) data.get("totalAmount");
        request.setAttribute("outTradeNo", outTradeNo);
        request.setAttribute("tradeNo", tradeNo);
        request.setAttribute("totalAmount", totalAmount);
        log.info("######支付宝同步回调CallBackController######synCallBack结束,params:{}", params);

        //正式版本，域名不能写死，需要从配置文件获取
        String htmlForm = "<form name='punchout_form' method='post' action='http://nut.nat300.top/alibaba/callBack/synSuccessPage' >" +
                "<input type='hidden' name='outTradeNo' value='"+outTradeNo+"'>" +
                "<input type='hidden' name='tradeNo' value='"+tradeNo+"'>" +
                "<input type='hidden' name='totalAmount' value='"+totalAmount+"'>" +
                "<input type='submit' value='立即支付' style='display:none'></form><script>document.forms[0].submit();</script>";
        writer.println(htmlForm);
    }

    @RequestMapping(value = "/synSuccessPage", method = RequestMethod.POST)
    public String synSuccessPage(String outTradeNo, String tradeNo, String totalAmount, HttpServletRequest request) {
        request.setAttribute("outTradeNo", outTradeNo);
        request.setAttribute("tradeNo", tradeNo);
        request.setAttribute("totalAmount", totalAmount);
        return PAY_SUCCESS;
    }

    //异步通知
    @RequestMapping("/notifyUrl")
    @ResponseBody
    public String asyncCallBack(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        response.setContentType("text/html;charset=utf-8");
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("######支付宝异步回调CallBackController######synCallBack开始,params:{}", params);
        String result = callBackServiceFeign.asyncCallBack(params);
        return result;
    }

}
